# -*- coding: utf-8 -*-

import logging
import redis
import json
from traceback import print_exc


logger = logging.getLogger()


class RedisClient:
    def __init__(self):
        self.pool = ""
        self.redis_client = ""
        self.MY_ASSIST_RANK = 'MY_ASSIST_RANK'

    def init_from_app(self, app):
        self.redis_client = redis.Redis(host=app.config['REDIS_SERVER_HOST'], port=6379, db=0)

    def add_client_pool(self, client_id, active_client):
        try:
            active_client_pool = ''.join(['ACTIVE_CLIENT_POOL'])
            self.redis_client.hset(active_client_pool, client_id, json.dumps(active_client))
        except:
            print_exc

    def get_client(self, client_id):
        try:
            active_client_pool = ''.join(['ACTIVE_CLIENT_POOL'])
            print(active_client_pool)
            active_client = self.redis_client.hget(active_client_pool, client_id)
            if active_client:
                return json.loads(active_client)
            else:
                return None
        except:
            print_exc


    def radd_offline_message(self, message, sender_id, receiver_id):
        try:
            offline_message_list = ''.join(['OFFLINE_MESSAGE_LIST', '-', str(sender_id), '-',str(receiver_id)])
            print(offline_message_list)
            print(message)
            self.redis_client.rpush(offline_message_list, message)
        except:
            print_exc

    def get_offline_message(self, sender_id, receiver_id):
        try:
            offline_message_list = ''.join(['OFFLINE_MESSAGE_LIST', '-', str(sender_id), '-', str(receiver_id)])
            results = self.redis_client.lrange(offline_message_list, 0, -1)
            print(results)
            return [eval(x.decode('utf-8')) for x in results]
        except:
            print_exc(limit=5)
        return None

    def pop_offline_message(self, sender_id, receiver_id):
        try:
            offline_message_list = ''.join(['OFFLINE_MESSAGE_LIST', '-', str(sender_id), '-', str(receiver_id)])
            results = self.redis_client.lpop(offline_message_list)
            return eval(results.decode('utf-8')) if results else None
        except:
            print_exc(limit=5)
        return None

    def del_offline_message(self, sender_id, receiver_id):
        try:
            offline_message_list = ''.join(['OFFLINE_MESSAGE_LIST', '-', str(sender_id), '-', str(receiver_id)])
            result = self.redis_client.ltrim(offline_message_list, 1, 0)
            return result

        except:
            print_exc(limit=5)
        return False